﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Reflection;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Bson.Serialization;

namespace Jack.DataScience.Data.JsonConverters
{
    public class BsonDocumentConverter : JsonConverter<BsonDocument>
    {
        public override void WriteJson(JsonWriter writer, BsonDocument value, JsonSerializer serializer)
        {
            var bson = value as BsonDocument;
            if (bson == null)
            {
                var jObject = JObject.FromObject(null);
                jObject.WriteTo(writer);
            }
            else
            {
                var jObject = JObject.Parse(bson.ToJson());
                jObject.WriteTo(writer);
            }

        }

        public override BsonDocument ReadJson(JsonReader reader, Type objectType, BsonDocument existingValue, bool hasExistingValue, JsonSerializer serializer)
        {

            var jObject = JObject.Load(reader);
            BsonDocument bson = null;
            if (jObject.Type != JTokenType.Null)
            {
                bson =  BsonDocument.Parse(JsonConvert.SerializeObject(jObject));
            }
            return bson;
        }
    }
}
